<script setup>
const props = defineProps({
  mapPoints: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(["loadComplete"]);

let localCenter = ref({ lng: 121.57303, lat: 29.82746 });
const zoom = ref(14);

const mapInfo = ref(null);

const init = async ({ map, BMap }) => {
  if (map) {
    setTimeout(() => {
      mapInfo.value = map;
      localCenter.value = {
        lng: props.mapPoints[0]["经度"],
        lat: props.mapPoints[0]["纬度"]
      };
      props.mapPoints.forEach(marker => {
        const point = new BMap.Point(marker["经度"], marker["纬度"]);

        map.centerAndZoom(point, zoom.value);
        const markerInstance = new BMap.Marker(point);

        // 创建信息窗口
        let opts = {
          title: marker["站点名称"] // 信息窗口标题
        };
        let str = "";
        for (let k in marker) {
          if (k !== "经度" && k !== "纬度" && k !== "站点名称") {
            str += `<p>${k}：${marker[k]}</p>`;
          }
        }

        let infoWindow = new BMap.InfoWindow(str, opts); // 创建信息窗口对象

        // 添加点击事件 - 点击标记打开信息窗口
        markerInstance.addEventListener("click", e => {
          map.openInfoWindow(infoWindow, e.point); // 打开信息窗口
        });

        map.addOverlay(markerInstance);
        emit("loadComplete");
      });
    }, 0);

    // 添加控件到地图
  }
};

// 鼠标滚动时关闭信息窗口
const zoomStart = map => {
  mapInfo.value.closeInfoWindow();
};
</script>

<template>
  <div class="mapBox">
    <baidu-map
      class="bm-view"
      :center="localCenter"
      :zoom="zoom"
      :map-click="false"
      :scroll-wheel-zoom="true"
      @ready="map => init(map)"
      @zoomstart="map => zoomStart(map)"
    />
  </div>
</template>

<style scoped lang="scss">
.mapBox {
  width: 100%;
  height: 100%;
  .bm-view {
    width: 100%;
    min-width: 330px;
    border-collapse: collapse;
    height: 300px;
  }

  /*
    去除百度地图版权
    去除百度地图右上角平移缩放控件的市县区文字
  */
  ::v-deep .anchorBL,
  ::v-deep .anchorTR {
    display: none;
    visibility: hidden;
  }
}
</style>
